#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: home.py
@contact: zwb15083976291@163.com
@time: 2022/03/12
"""
import calendar
from datetime import date, datetime, timedelta

from django.db.models import Count, Sum, Q
from django.db.models.functions import TruncDay
from django.utils.decorators import method_decorator

from common.models import BlogComments, BlogArticle, BlogMessage, BlogVisits, BlogCategorie, BlogTag
from utils.responses import CommonResponse
from utils.user_authentication import allow_admin_user
from utils.views.views import GenericAPIView


@method_decorator(allow_admin_user, name='dispatch')
class AdminHomeView(GenericAPIView):

    def get(self, request):
        # 评论数量
        comments_count = BlogComments.objects.count()
        # 文章数量
        articles_count = BlogArticle.objects.count()
        # 留言数量
        messages_count = BlogMessage.objects.count()
        # 总访问量
        visits_count = BlogVisits.objects.aggregate(Sum('visits_count')).get("visits_count__sum", 0)
        number_statis_data = dict(comments_count=comments_count, articles_count=articles_count,
                                  messages_count=messages_count, visits_count=visits_count)
        # 访问量线表
        week_visits_list = BlogVisits.objects.order_by('-visits_date').all()[:7]

        week_visits_data = dict(time_axis=[], line_data=[])
        if week_visits_list:
            week_visits_list = week_visits_list[::-1]
            week_visits_data['time_axis'] = [item.visits_date for item in week_visits_list]
            week_visits_data['line_data'] = [item.visits_count for item in week_visits_list]

        # 文章提交详情
        articles_commit = BlogArticle.objects.annotate(day=TruncDay('create_time')).values('day').annotate(
            commit_count=Count('day')).filter(
            create_time__year=datetime.now().year).order_by('-commit_count').all()

        now = datetime.now()
        end_date = datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1])
        # 返回的文章提交详情
        articles_commit_data = dict(end_date=end_date.strftime("%Y-%m-%d"), data=[])
        if articles_commit:
            articles_commit_data['data'] = [
                dict(date=item.get("day").strftime("%Y-%m-%d"), count=item.get("commit_count")) for
                item in articles_commit]
        # 文章访问量排行
        visit_ranking = BlogArticle.objects.order_by('-reading_quantity').values('articles_title',
                                                                                 'reading_quantity').all()[:5]

        visit_ranking_data = dict(articles_name=[], visits_count=[])
        if visit_ranking:
            visit_ranking = visit_ranking[::-1]
            visit_ranking_data = dict(articles_name=[item['articles_title'] for item in visit_ranking],
                                      visits_count=[item['reading_quantity'] for item in visit_ranking])

        # 获取分类文章统计
        categorys = BlogCategorie.objects.filter(~Q(categorie_count=0)).order_by('-categorie_count').values(
            'categorie_name', 'categorie_count').all()
        category_data = []
        if categorys:
            category_data = [{'name': item['categorie_name'], 'value': item['categorie_count']} for item in categorys]

        # 标签统计
        tags = BlogTag.objects.filter(~Q(articles_count=0)).order_by('-articles_count').values(
            'tag_name', 'articles_count').all()
        tags_data = []
        if tags:
            tags_data = [{'name': item['tag_name'], 'value': item['articles_count']} for item in tags]

        word_cloud = BlogMessage.objects.values("blog_message").filter(audit__in=[0, 1]).annotate(
            value=Count('blog_message')).all()

        # 标签名称
        tags_name = BlogTag.objects.values('id', 'tag_name').order_by('-articles_count').all()[:20]
        tags_name_data = []
        if tags_name:
            tags_name_data = [{'id': item['id'], 'name': item['tag_name']} for item in tags_name]

        # 词云
        word_cloud_data = []
        if word_cloud:
            word_cloud_data = [{'name': item['blog_message'], 'value': item['value']} for item in word_cloud]
        return CommonResponse(
            data=dict(number_statis=number_statis_data, week_visits=week_visits_data,
                      articles_commit=articles_commit_data, articles_visit_ranking=visit_ranking_data,
                      category_data=category_data, tags_data=tags_data, tags_name=tags_name_data,
                      word_cloud=word_cloud_data))
